<template>
  <div>
    <div class="login-container" id='login'>
      <el-form class="login-form"
               autoComplete="on"
               :rules="loginRules"
               :model="loginForm"
               ref="loginForm"
               label-position="left">
        <div class="title-container">
          <h3 class="title">后台管理系统</h3>
        </div>
        <el-tabs v-model="activeName" @tab-click="handleLoginTabClick">
          <el-tab-pane label="账号密码" name="passwordLogin">
            <el-form-item prop="userName">
            <span class="svg-container svg-container_login">
              <icon name="user"></icon>
            </span>
              <el-input name="userName"
                        type="text"
                        v-model="loginForm.userName"
                        autoComplete="on"
                        placeholder="登录名" />
            </el-form-item>
            <el-form-item prop="password">
            <span class="svg-container">
              <icon name="lock"></icon>
            </span>
              <el-input name="password"
                        :type="passwordBlur?'password':'text'"
                        @keyup.enter.native="handleLogin"
                        v-model="loginForm.password"
                        autoComplete="on"
                        placeholder="密码">
                <i slot="suffix"
                   class="el-icon-view"
                   @click="changePasswordBlur"></i>
              </el-input>
            </el-form-item>
            <el-form-item prop="graphCode">
            <span class="svg-container">
              <icon name="tags"></icon>
            </span>
              <el-input style="width:40%;"
                        name="graphCode"
                        type="graphCode"
                        @keyup.enter.native="handleLogin"
                        v-model="loginForm.graphCode"
                        placeholder="验证码" />
              <img v-bind:src="graphCodeUrl"
                   style="float: right; cursor:pointer;"
                   @click="getPermitGraphCode()">
            </el-form-item>
            <el-button type="primary"
                       class="loginBtn"
                       @click.native.prevent="handleLogin">
              登录
            </el-button>
          </el-tab-pane>
          <el-tab-pane label="快捷登录" name="msgCodeLogin">
            <el-form-item prop="phoneNumber">
              <span class="svg-container svg-container_login">
                <icon name="phone"></icon>
              </span>
              <el-input name="phoneNumber"
                        type="text"
                        v-model="loginForm.phoneNumber"
                        autoComplete="on"
                        placeholder="手机号" />
            </el-form-item>
            <el-form-item prop="graphCode">
              <span class="svg-container">
                <icon name="tags"></icon>
              </span>
              <el-input style="width:40%;"
                        name="graphCode"
                        type="graphCode"
                        @keyup.enter.native="handleLogin"
                        v-model="loginForm.graphCode"
                        placeholder="验证码" />
              <img v-bind:src="graphCodeUrl"
                   style="float: right; cursor:pointer;"
                   @click="getPermitGraphCode()">
            </el-form-item>
            <el-form-item prop="msgCode">
              <span class="svg-container">
                <icon name="envelope-o"></icon>
              </span>
              <el-input name="msgCode" style="width:50%;display:inline-block;"
                        v-model="loginForm.msgCode"
                        placeholder="短信验证码">
              </el-input>
              <el-button type="primary"
                         style="float: right; display:inline-block;margin-top: 5px;"
                         @click="getLoginMsgCode"
                         :disabled="msgCode.disable">
                {{ msgCode.display }}
              </el-button>
            </el-form-item>
            <el-button type="primary"
                       class="loginBtn"
                       @click.native.prevent="handleMsgCodeLogin"
                       :disabled="msgCode.loginButton">
              登录
            </el-button>
          </el-tab-pane>
          <el-tab-pane label="微信登录" name="wechatLogin">
            <el-form-item prop="userName">
              <vue-qr :text="qrCodeUrl"
                      :size="200"
                      :callback="qrcodeCallBack"
                      style="text-align:center;margin: 60px;"/>
              <div style="text-align:center; color:#eee;margin-bottom: 10px">{{ loginStatus }}</div>
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </div>
  </div>

</template>

<script>

export default {
  name: 'login',
  data () {
    return {
      activeName: 'passwordLogin',
      loginRules: {
        userName: [
          { required: true, trigger: 'blur', message: '用户名不能为空' }],
        password: [
          { required: true, trigger: 'blur', message: '密码不能为空' }],
        graphCode: [
          { required: true, trigger: 'blur', message: '验证码不能为空' },
          { min: 4, max: 4, message: '请输入4位验证码' }],
        phoneNumber: [
          { required: true, trigger: 'blur', message: '手机号不能为空' },
          { min: 11, max: 11, message: '请输入11位手机号' }],
        msgCode: [{ required: true, trigger: 'blur', message: '短信验证码不能为空' }]
      },
      loginForm: {
        userName: '',
        password: '',
        graphCode: '',
        phoneNumber: '',
        msgCode: ''
      },
      msgCode: {
        display: '获取验证码',
        disable: false,
        startTimeStamp: '',
        internalTime: 60000,
        disableTimer: {},
        secondTimer: {},
        loginButton: true
      },
      graphCodeUrl: '',
      passwordBlur: true,
      qrCodeUrl: '',
      qrCodeDialog: false,
      loginStatus: '请打开小程序扫码登录',
      ssoTimer: {},
      ssoDisplayTimer: {}
    }
  },
  mounted () {
    this.getPermitGraphCode()
    // this.getMsgCodeInternalTime()
  },
  methods: {
    changePasswordBlur () {
      this.passwordBlur = !this.passwordBlur
    },
    handleLoginTabClick (tab, event) {
      if (tab.name === 'wechatLogin') {
        this.ssoLogin()
      } else if (tab.name === 'msgCodeLogin') {
        this.getPermitGraphCode('LOGIN_MSG_CODE')
      } else {
        this.getPermitGraphCode()
        this.closeQRCodeDialog()
      }
    },
    getToken () {
      return this.$store.getters.token
    },
    getPermitGraphCode (codeType = 'LOGIN_CAPTCHA') {
      const _this = this
      _this.$store.dispatch('fetchToken').then(token => {
        _this.graphCodeUrl = _this.baseUrl + _this.apiType.common.getCaptcha.url + '?token=' + token + '&captchaType=' + codeType + '&d=' + Math.random()
      })
      /* .catch(errData => {
        const message = errData.data.errMsg
        _this.$alert(message)
      }) */
    },
    // getMsgCodeInternalTime () {
    //   const _this = this
    //   this.fetch(this.apiType.common.getParam,
    //     {parameterId: 'MSG_VERIFICATION_INTERNAL'},
    //     null,
    //     responseData => {
    //       _this.msgCode.internalTime = responseData.data * 1000
    //     })
    // },
    async getLoginMsgCode () {
      const _this = this
      this.fetch(
        this.apiType.common.getMsgCode,
        {
          token: await _this.$store.dispatch('fetchToken'),
          graphCode: this.loginForm.graphCode,
          msgCodeType: 'LOGIN_MSG_CODE',
          phoneNumber: this.loginForm.phoneNumber
        },
        null,
        responseData => {
          _this.msgCode.startTimeStamp = Date.now()
          _this.msgCode.disable = true
          _this.msgCode.disableTimer = setTimeout(this.disableGetMsgCode, this.msgCode.internalTime)
          _this.msgCode.secondTimer = setInterval(this.changeGetMsgCodeDisplay, 1000)
          _this.msgCode.loginButton = false
          _this.msgCode.internalTime = responseData.data * 1000
        })
    },
    handleMsgCodeLogin () {
      const _this = this
      const userInfo = {
        loginMsgCode: this.loginForm.msgCode,
        phoneNumber: this.loginForm.phoneNumber
      }
      _this.$store.dispatch('msgCodeLogin', userInfo).then(respData => {
        _this.setLocalStorage('token', respData.data.accessToken)
        _this.setLocalStorage('name', respData.data.name)
        _this.setLocalStorage('operator', respData.data.customerNumber)
        _this.setLocalStorage('refreshToken', respData.data.refreshToken)
        _this.$router.push({ path: '/' })
      })
      /* .catch(errData => {
        const message = errData.data.errMsg
        _this.$alert(message)
        this.getPermitGraphCode()
      }) */
    },
    disableGetMsgCode () {
      this.msgCode.disable = false
      this.msgCode.display = '获取验证码'
      clearTimeout(this.msgCode.disableTimer)
      clearTimeout(this.msgCode.secondTimer)
    },
    changeGetMsgCodeDisplay () {
      this.msgCode.display = '重新获取(' + (60 -
        parseInt((Date.now() - this.msgCode.startTimeStamp) / 1000)) + ')'
    },
    handleLogin () {
      const _this = this
      const userInfo = {
        loginId: this.loginForm.userName,
        password: this.loginForm.password,
        graphCode: this.loginForm.graphCode
      }
      _this.$store.dispatch('login', userInfo).then(respData => {
        _this.setLocalStorage('token', respData.data.accessToken)
        _this.setLocalStorage('refreshToken', respData.data.refreshToken)
        _this.setLocalStorage('name', respData.data.name)
        _this.setLocalStorage('operator', respData.data.customerNumber)
        _this.$router.push({ path: '/' })
      })
      /** .catch(errData => {
            const message = errData.data.errMsg
            _this.$alert(message)
            this.getPermitGraphCode()
          })
       */
    },
    closeQRCodeDialog () {
      this.qrCodeDialog = false
      clearTimeout(this.ssoTimer)
      clearTimeout(this.ssoDisplayTimer)
    },
    ssoDisplay () {
      this.loginStatus += '.'
      if (this.loginStatus.length > 15) {
        this.loginStatus = this.loginStatus.substring(0, 10)
      }
    },
    sso () {
      /*
      const _this = this
      _this.$store.dispatch('SsoLogin', this.getToken()).then(respData => {
        clearTimeout(this.ssoTimer)
        _this.setSessionStorage('auth_token', respData.data.token)
        _this.setSessionStorage('name', respData.data.name)
        _this.setSessionStorage('operator', respData.data.userName)
        _this.$router.push({ path: '/' })
      }).catch(errData => {
        this.ssoTimer = setTimeout(this.sso, 3000)
      })
       */
    },
    async ssoLogin () {
      this.qrCodeUrl = await this.$store.dispatch('fetchToken')
      this.ssoTimer = setTimeout(this.sso, 5000)
      this.ssoDisplayTimer = setInterval(this.ssoDisplay, 1000)
    },
    qrcodeCallBack () {
      console.log('qrcodeCallBack')
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
$bg: #2d3a4b;
$light_gray: #eee;

/* reset element-ui css */
.login-container {
  .login-form {
    .el-form-item__error {
      position: absolute;
    }
  }

  .el-input {
    display: inline-block;
    height: 47px;
    width: 89%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;

      &:-webkit-autofill {
        -webkit-box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: #fff !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
    margin-bottom: 20px;
  }

  .el-form-item__content {
    display: block;
    margin-left: 0px !important;
  }

  .el-form-item__error {
    position: absolute;
    padding-top: 5px !important;
  }

  .el-tabs__item {
    color: #889aa4 !important;
  }
}
</style>
<style rel="stylesheet/scss" lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.login-container {
  position: fixed;
  height: 100%;
  width: 100%;
  background-color: $bg;

  .login-form {
    position: absolute;
    left: 0;
    right: 0;
    width: 400px;
    padding: 35px 35px 15px 35px;
    margin: 120px auto;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;

    &_login {
      font-size: 20px;
    }
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      font-weight: 400;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }

    .set-language {
      color: #fff;
      position: absolute;
      top: 5px;
      right: 0px;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }

  .thirdparty-button {
    position: absolute;
    right: 35px;
    bottom: 28px;
  }

  .el-icon-view {
    vertical-align: middle;
    padding: 16px 5px 6px 15px;
  }

  .loginBtn {
    width: 100%;
    margin-bottom:30px;
    float: left;
  }

  .ssoBtn {
    width: 35%;
    margin-right: 20px;
    float: right;
  }

  .qr-container {
    width: 100%;
    margin: 0 auto;
    text-align: center;
  }
}
</style>
